package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {
    public String paymentInfo_OK(Integer id) {
        return "线程组：" + Thread.currentThread().getName() + " paymentInfo_OK,id=" + id + "，随机码:" + IdUtil.randomUUID();
    }

    @HystrixCommand(fallbackMethod = "payment_error",
            commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")})
    public String paymentInfo_TimeOut(Integer id) {
        int time = 3;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程组：" + Thread.currentThread().getName() + " paymentInfo_TimeOut,id=" + id + ",延迟:" + time + "秒" + "，随机码:" + IdUtil.randomUUID();
    }

    @HystrixCommand(fallbackMethod = "payment_error",
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
            })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException();
        } else {
            return "线程组：" + Thread.currentThread().getName() + " paymentCircuitBreaker,id=" + id + "，随机码:" + IdUtil.randomUUID();
        }

    }

    public String payment_error(Integer id) {
        return "线程组：" + Thread.currentThread().getName() + " 服务异常或者超时,id=" + id + "，随机码:" + IdUtil.randomUUID();

    }
}
